package com.ttbj.controller.websocket;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.socket.TextMessage;

import com.ttbj.api.order.OrderService;
import com.ttbj.util.ViewDataUtil;
import com.ttbj.websocket.PushSalMessageHandler;

@Controller
public class PushMessageController {
	
	@Autowired
	private OrderService orderService;
	
	
	@Bean	//这个注解会从Spring容器拿出Bean
	public PushSalMessageHandler infoHandler(){
		return new PushSalMessageHandler();
	}
	
	/**
	 * 给与websocket连接的发送消息
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/pm/send_msg.htm", method=RequestMethod.GET, produces={"text/html;charset=UTF-8;","application/json;"})
	@ResponseBody
	public String send(HttpServletRequest request, HttpServletResponse response){
		//获取最新的订单id
		Long orderId = this.orderService.findNewestOrderInfo();
		try {
			infoHandler().sendMessageToUsers(new TextMessage("有新的预订单信息！"));
			return ViewDataUtil.buildSuccessJson("消息已推送");
		} catch (Exception e) {
			return ViewDataUtil.buildFailureJson(1, "消息推送失败");
		}
	}
}
